"""
@author: Sergiy Tsymbalyuk
"""

import logging

from datetime import date, timedelta

from pylons import tmpl_context as c, request, url
from pylons.i18n import lazy_ugettext as _
from pylons.controllers.util import redirect
from sqlalchemy import func

from webhelpers.html import literal

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import in_group

from chowa.lib.site.navigation import Tab
from chowa.model.organization import Division, District
from chowa.lib.helpers import url_gen
from hrms.lib.base import BaseController, render, Session
from hrms.model.person import Employee, EmploymentHistory

log = logging.getLogger(__name__)

@ControllerProtector(in_group('hrms.administrators'))
class BriefController(BaseController):
    __primary_tabs__ = [
        [
            Tab(params=dict(action='index'),
                caption=_('Reports')),
            Tab(params=dict(action='birthdays'),
                caption=_('Birthdays')),
            Tab(params=dict(action='staff'),
                caption=_('Staff')),
            Tab(params=dict(action='age'),
                caption=_('Age')),
            Tab(params=dict(action='experience'),
                caption=_('Experience')),
        ]
    ]
    
    def __before__(self):
        c.main_heading = _('Reports')
        self.district_id = request.params.get('district')
        c.district_id = self.district_id
        districts = Session.query(District).all()
        c.districts = [('', _('All'))] + [(d.id, d.name) for d in districts]
    
    def index(self):
        return render('/hrms/brief/index.html')
    
    def generate(self):
        brief = request.params.get('brief')
        return redirect(url_gen(action=brief))

    def birthdays(self):
        month = request.params.get('month')
        if not month:
            today = date.today()
            month = today.month
            
        query = Session.query(Employee) \
            .filter_by(is_employee=True) \
            .filter(func.month(Employee.born) == month)
        if self.district_id:
            query = query.join(Division) \
                .filter(Division.district_id == self.district_id)
        c.employees = query.all()
        c.month = int(month)
        c.district = Session.query(District).get(self.district_id) if self.district_id else _('All')
        
        return render('/hrms/brief/birthdays.html')
    
    def staff(self):
        query = Session.query(Employee).filter_by(is_employee=True)
        if self.district_id:
            query = query.join(Division) \
                .filter(Division.district_id == self.district_id)
        c.males = query.filter(Employee.gender == 'M').all()
        c.females = query.filter(Employee.gender == 'F').all()
        
        return render('/hrms/brief/staff.html')
    
    def age(self):
        today = date.today()
        query = Session.query(Employee).filter(Employee.is_employee == True)
        if self.district_id:
            query = query.join(Division) \
                .filter(Division.district_id == self.district_id)
        def staff(gender=None):
            staff_query = query
            if gender:
                staff_query = staff_query.filter(Employee.gender == gender)
            return staff_query.count()
        def age(min=None, max=None, gender=None):
            age_query = query
            if min:
                born = today.replace(year=today.year-min)
                age_query = age_query.filter(Employee.born <= born)
            if max:
                born = today.replace(year=today.year-max-1)
                age_query = age_query.filter(Employee.born > born)
            if gender:
                age_query = age_query.filter(Employee.gender == gender)
            return age_query.count()
        c.staff = staff
        c.age = age
        return render('/hrms/brief/age.html')
    
    def experience(self):
        today = date.today()
        query = Session.query(Employee).filter(Employee.is_employee == True)
        if self.district_id:
            query = query.join(Division) \
                .filter(Division.district_id == self.district_id)
        c.employees = query.all()
        def xp(employee, filter=None):
            days = 0
            for record in employee.history:
                is_state = (filter == 'state') and record.is_state
                is_treasury = (filter == 'treasury') and record.is_treasury
                if (is_state or is_treasury or not filter):
                    try:
                        delta = (record.ended or today) - record.started
                        days += delta.days
                    except Exception as e:
                        print e
            try:
                d = date(1, 1, 1) + timedelta(days)
            except:
                return _('error')
            xp_str = _('%2dy %2dm %2dd') % (d.year-1, d.month-1, d.day-1)
            return literal(xp_str.replace(' ', '&nbsp;'))
        c.xp = xp
        return render('/hrms/brief/experience.html')
